import { useState, useEffect } from 'react'
import { 
  Button,
  Grid,
  Toast
} from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import UserRoleDisplay from '../../components/UserRoleDisplay'
import FaceCamera from '../../components/FaceCamera'
import FaceQualityCheck from '../../components/FaceQualityCheck'
import { detectFace, fileToBase64, addUserToFaceSet, createFaceSet, queryFaceSetUsers } from '../../api/faceRecognition'
import { checkFaceRegistered } from '../../api/faceLogin'
import './index.css'

function Mine() {
  const navigate = useNavigate()

  // 人脸注册相关状态
  const [showFaceCamera, setShowFaceCamera] = useState(false)
  const [faceQualityResult, setFaceQualityResult] = useState<{
    isValid: boolean
    message: string
    details?: Record<string, unknown>
    imageData?: string
    faceData?: Record<string, unknown>
  } | null>(null)
  const [showFaceQualityCheck, setShowFaceQualityCheck] = useState(false)
  const [isFaceRegistering, setIsFaceRegistering] = useState(false)
  const [isFaceRegistered, setIsFaceRegistered] = useState(false)

  // 检查用户是否已注册人脸
  useEffect(() => {
    const checkFaceStatus = async () => {
      const userId = localStorage.getItem('userId')
      if (userId) {
        try {
          const response = await checkFaceRegistered(userId)
          if (response.data?.status === '0000') {
            setIsFaceRegistered(response.data.result?.isRegistered || false)
          }
        } catch (error) {
          console.error('检查人脸注册状态失败:', error)
        }
      }
    }
    checkFaceStatus()
  }, [])

  const goToFollowedDoctors = () => {
    navigate('/followed-doctors')
  }

  // 人脸注册相关处理函数
  const handleFaceRegister = () => {
    if (isFaceRegistered) {
      Toast.show('您已注册人脸，如需重新注册请联系管理员')
      return
    }
    setShowFaceCamera(true)
  }

  const handleFaceCapture = async (imageData: string) => {
    try {
      setIsFaceRegistering(true)
      setShowFaceCamera(false)
      
      // 将base64图片转换为File对象
      const response = await fetch(imageData)
      const blob = await response.blob()
      const file = new File([blob], 'face.jpg', { type: 'image/jpeg' })
      
      // 转换为base64格式
      const base64 = await fileToBase64(file)
      
      // 进行人脸检测和质量评估
      const detectResult = await detectFace(base64)
      
      if (!detectResult.success) {
        Toast.show(detectResult.message)
        setIsFaceRegistering(false)
        return
      }

      // 设置质量检测结果
      setFaceQualityResult({
        isValid: true,
        message: detectResult.message,
        details: detectResult.data?.quality,
        imageData: base64,
        faceData: detectResult.data
      })
      
      setShowFaceQualityCheck(true)
      setIsFaceRegistering(false)
    } catch (error) {
      console.error('人脸捕获处理错误:', error)
      Toast.show('人脸识别失败，请重试')
      setIsFaceRegistering(false)
    }
  }

  const handleFaceRetry = () => {
    setShowFaceQualityCheck(false)
    setFaceQualityResult(null)
    setShowFaceCamera(true)
  }

  const handleFaceConfirm = async () => {
    if (!faceQualityResult?.imageData) {
      Toast.show('人脸数据异常，请重新拍摄')
      return
    }

    try {
      setIsFaceRegistering(true)
      setShowFaceQualityCheck(false)
      
      const userId = localStorage.getItem('userId')
      if (!userId) {
        Toast.show('用户信息异常，请重新登录')
        return
      }

      // 使用百度云人脸库管理进行注册
      const groupId = 'user_faces'
      const userInfo = localStorage.getItem('userName') || localStorage.getItem('email') || '用户'
      
      // 添加用户到人脸库
      const addResult = await addUserToFaceSet(
        groupId,
        userId,
        userInfo,
        faceQualityResult.imageData
      )
      
      if (addResult.success) {
        setIsFaceRegistered(true)
        Toast.show('人脸注册成功！')
        
        // 显示详细成功信息
        Toast.show({
          content: `人脸注册成功！\n用户: ${userInfo}\n人脸库: ${groupId}\n现在可以使用人脸登录了！`,
          duration: 3000,
          position: 'center'
        })
      } else {
        // 如果添加失败，可能是人脸库不存在，尝试创建
        if (addResult.message.includes('group_id not exist')) {
          const createResult = await createFaceSet(groupId)
          if (createResult.success) {
            // 重新尝试添加用户
            const retryResult = await addUserToFaceSet(
              groupId,
              userId,
              userInfo,
              faceQualityResult.imageData
            )
            if (retryResult.success) {
              setIsFaceRegistered(true)
              Toast.show('人脸注册成功！')
              
              // 显示详细成功信息
              Toast.show({
                content: `人脸注册成功！\n用户: ${userInfo}\n人脸库: ${groupId}\n现在可以使用人脸登录了！`,
                duration: 3000,
                position: 'center'
              })
              
              // 查询人脸库验证注册结果
              setTimeout(async () => {
                const queryResult = await queryFaceSetUsers(groupId)
                if (queryResult.success && queryResult.data) {
                  console.log('人脸库中的用户列表:', queryResult.data.user_list)
                  Toast.show({
                    content: `验证成功！\n人脸库中共有 ${queryResult.data.user_list.length} 个用户`,
                    duration: 2000
                  })
                } else {
                  console.error('查询人脸库失败:', queryResult.message)
                }
              }, 1000)
            } else {
              Toast.show(retryResult.message || '人脸注册失败')
            }
          } else {
            Toast.show(createResult.message || '创建人脸库失败')
          }
        } else {
          Toast.show(addResult.message || '人脸注册失败')
        }
      }
    } catch (error) {
      console.error('人脸注册错误:', error)
      Toast.show('人脸注册失败，请重试')
    } finally {
      setIsFaceRegistering(false)
      setFaceQualityResult(null)
    }
  }

  const handleFaceCameraClose = () => {
    setShowFaceCamera(false)
    setIsFaceRegistering(false)
  }

  // 调试查询功能已迁移至独立页面

  return (
    <div className="mine-container">
      {/* 蓝色头部区域 */}
      <div className="blue-header">
        <div className="header-title">我的工作室</div>
        
        <div className="header-actions">
          <Button className="header-action-btn">扫一扫</Button>
          <Button className="header-action-btn" onClick={() => navigate('/message')}>妙手客服</Button>
        </div>
        
        <div className="profile-section">
          <div className="profile-left">
            <div className="profile-avatar">👨‍⚕️</div>
            <div className="profile-info">
              <div className="name-row">
                <span className="doctor-name">杨*淮</span>
                <span className="cert-tag">已认证</span>
                <UserRoleDisplay />
              </div>
              <div className="specialty">消化内科 | 主治医师</div>
            </div>
          </div>
          <div className="homepage-btn">
            我的主页 &gt;
          </div>
        </div>
      </div>

      {/* 白色内容区域 */}
      <div className="white-content">
      
      

        {/* 消息卡片 */}
        <div className="message-card">
          <div className="message-avatar">👤</div>
          <div className="message-content">
            <div className="message-text">
              患者"刘**"给您写了感谢信:非常感谢医生帮助我...
            </div>
          </div>
          <div className="unread-dot"></div>
        </div>

        {/* 活动卡片 */}
        <div className="activity-section">
          <div className="activity-card left">
            <div className="card-badge">12</div>
            <div className="card-icon">📧</div>
            <div className="card-content">
              <div className="card-title">最新活动</div>
              <div className="card-subtitle">现金红包等你拿</div>
            </div>
          </div>
          
          <div className="activity-card right">
            <div className="card-tag">今日未签</div>
            <div className="card-icon">📅</div>
            <div className="card-content">
              <div className="card-title">每日签到</div>
              <div className="card-subtitle">累计签到112天</div>
            </div>
          </div>
        </div>

        {/* 功能网格 */}
        <div className="function-grid-card">
          <div className="card-title-section">
            <h3>快捷功能</h3>
          </div>
          <div className="grid-container">
            <div className="grid-item">
              <div className="grid-icon">💊</div>
              <div className="grid-text">用药建议</div>
            </div>
            <div className="grid-item">
              <div className="grid-icon">🏥</div>
              <div className="grid-text">我的药房</div>
            </div>
            <div className="grid-item" onClick={goToFollowedDoctors}>
              <div className="grid-icon">👥</div>
              <div className="grid-text">我的关注</div>
            </div>
            <div className="grid-item" onClick={() => navigate('/permission-test')}>
              <div className="grid-icon">🔒</div>
              <div className="grid-text">权限测试</div>
            </div>
            <div className="grid-item" onClick={() => navigate('/change-password')}>
              <div className="grid-icon">🔐</div>
              <div className="grid-text">修改密码</div>
            </div>
            <div className={`grid-item ${isFaceRegistering ? 'face-registering' : isFaceRegistered ? 'face-registered' : ''}`} onClick={handleFaceRegister}>
              <div className="grid-icon">👤</div>
              <div className="grid-text">
                {isFaceRegistering ? '注册中...' : (isFaceRegistered ? '人脸已注册' : '人脸注册')}
              </div>
            </div>
            <div className="grid-item debug" onClick={() => navigate('/face-manage')}>
              <div className="grid-icon">🔍</div>
              <div className="grid-text">调试人脸库</div>
            </div>
            <div className="grid-item">
              <div className="grid-icon">📱</div>
              <div className="grid-text">患者报到码</div>
            </div>
            <div className="grid-item">
              <div className="grid-icon">💬</div>
              <div className="grid-text">问诊设置</div>
            </div>
            <div className="grid-item">
              <div className="grid-icon">📍</div>
              <div className="grid-text">报到设置</div>
            </div>
            <div className="grid-item">
              <div className="grid-icon">👍</div>
              <div className="grid-text">优选药房</div>
            </div>
            <div className="grid-item">
              <div className="grid-icon">👥</div>
              <div className="grid-text">我的团队</div>
            </div>
          </div>
        </div>

        {/* 问诊室 */}
        <div className="consultation-card">
          <div className="card-header">
            <h3>我的接诊室</h3>
            <div className="performance-metrics">
              <span className="metric">好评率100%</span>
              <span className="metric">感谢信 24</span>
              <span className="metric">锦旗 18</span>
            </div>
          </div>
          
          <Grid columns={4} gap={12}>
            <Grid.Item>
              <div className="grid-item">
                <div className="grid-icon">💬</div>
                <div className="grid-text">图文咨询</div>
              </div>
            </Grid.Item>
            <Grid.Item>
              <div className="grid-item">
                <div className="grid-icon">📞</div>
                <div className="grid-text">电话咨询</div>
              </div>
            </Grid.Item>
            <Grid.Item>
              <div className="grid-item">
                <div className="grid-icon">📹</div>
                <div className="grid-text">视频咨询</div>
              </div>
            </Grid.Item>
            <Grid.Item>
              <div className="grid-item">
                <div className="grid-icon">👍</div>
                <div className="grid-text">优选小店</div>
              </div>
            </Grid.Item>
          </Grid>
        </div>

        {/* 网络问诊抢单池 */}
        <div className="order-pool-card">
          <div className="order-pool-content">
            <div className="order-pool-info">
              <h3>网络问诊抢单池</h3>
              <p>快速抢单,赚知识费</p>
            </div>
            <Button className="grab-btn">
              立即抢题
            </Button>
          </div>
        </div>

        {/* 待处理任务 */}
        <div className="pending-tasks-card">
          <div className="card-title-section">
            <h3>待处理任务</h3>
          </div>
          
          <div className="tasks-tabs">
            <div className="tab-item active">
              <span className="tab-text">问诊待处理</span>
            </div>
            <div className="tab-item">
              <span className="tab-text">消息待回复</span>
            </div>
            <div className="tab-item">
              <span className="tab-text">复诊待开方</span>
            </div>
          </div>
          
          <div className="tasks-tabs">
            <div className="tab-item">
              <span className="tab-text">新患者</span>
            </div>
            <div className="tab-item">
              <span className="tab-text">门诊待接诊</span>
            </div>
            <div className="tab-item">
              <span className="tab-text">患者待接诊</span>
              <span className="team-tag">团队</span>
            </div>
          </div>
        </div>
      </div>

      {/* 人脸识别摄像头组件 */}
      <FaceCamera
        isVisible={showFaceCamera}
        onCapture={handleFaceCapture}
        onClose={handleFaceCameraClose}
        title="人脸注册"
      />

      {/* 人脸质量检测组件 */}
      {showFaceQualityCheck && faceQualityResult && (
        <FaceQualityCheck
          isVisible={showFaceQualityCheck}
          qualityResult={faceQualityResult as {
            isValid: boolean;
            message: string;
            details?: Record<string, unknown>;
            imageData?: string;
            faceData?: Record<string, unknown>;
          }}
          onRetry={handleFaceRetry}
          onConfirm={handleFaceConfirm}
        />
      )}
    </div>
  )
}

export default Mine
